package net.mingsoft.report_data.sao;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.mingsoft.base.util.JSONObject;
import net.mingsoft.basic.util.HttpRequest;
import net.mingsoft.report_data.sao.entity.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author gengfa
 * @date 2022/06/07
 */
@Service
@Slf4j
public class SgSao {
    @Value("${sg-api.baseUrl}")
    private String sgBaseUrl;

    @Value("${sg-api.admin}")
    private String admin;

    @Value("${sg-api.passwd}")
    private String passwd;

    @Resource
    ConcurrentMapCacheManager cacheManager;

    private static final String KEY_LOGIN_CACHE = "LOGIN_CACHE";
    private static final String KEY_AUTHORIZATION = "Authorization";

    private static final String FULL_URL_LOGIN = "https://10.1.3.3:5000/api/common/login";
    private static final String URL_DICT = "/childDictionary?majorKey=hnssx";
    private static final String URL_ALL_TOP_DATA = "/areaMonitoring/getAllTopData";
    private static final String URL_AREA_USER_UP = "/areaMonitoring/getAreaUserUp";
    private static final String URL_CURRENT_USER = "/areaMonitoring/getCurrentUser";

    @Scheduled(cron = "0 */10 * * * *")
    public void login() {
        log.info("[PROCESS][SG] auto refresh token");
        JSONObject object = new JSONObject();
        object.put( "userName", admin);
        object.put( "password", passwd);
        @SuppressWarnings(value = "unchecked")
        LinkedHashMap<String, String> result = (LinkedHashMap<String, String>) HttpRequest.postUnSsl(FULL_URL_LOGIN, HttpRequest.setContType(object));
        Objects.requireNonNull(cacheManager.getCache(KEY_LOGIN_CACHE)).put(KEY_AUTHORIZATION, result.get("data"));
        log.info("[PROCESS][SG] finished");
    }

    /**
     * 关注区域用户页
     */
    public AllTopDataEntity getAllTopData() {
        return (AllTopDataEntity) HttpRequest.get(sgBaseUrl + URL_ALL_TOP_DATA, getBearToken(), AllTopDataEntity.class);
    }

    /**
     * 获取市县字典
     * @return 字典
     */
    public Map<Integer,String> getProvinceDictionary() {
        String dictListString = (String) HttpRequest.get(sgBaseUrl + URL_DICT, getBearToken(), String.class);
        List<DictionaryDto> dictionaryDtoList = JSON.parseArray(dictListString, DictionaryDto.class);
        return dictionaryDtoList.stream().collect(Collectors.toMap(DictionaryDto::getValue, DictionaryDto::getName));
    }

    /**
     * 获取 重点区域-查询实时在线用户数曲线 (/areaMonitoring/getAreaUserUp)
     * @return 重点区域-查询实时在线用户数曲线 (/areaMonitoring/getAreaUserUp)
     */
    public AreaUserUpDto getAreaUserUp(String areaId, String taskId) {
        LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add( "areaId", areaId);
        params.add( "taskId", taskId);
        HttpHeaders headers = getBearToken();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        AreaUserUpEntity entity = (AreaUserUpEntity) HttpRequest.post(sgBaseUrl + URL_AREA_USER_UP, headers, params, AreaUserUpEntity.class);
        return entity.getData();
    }

    /**
     * 获取 重点区域实时监测-查询实时在线用户数 (/areaMonitoring/getCurrentUser)
     * @return 重点区域实时监测-查询实时在线用户数 (/areaMonitoring/getCurrentUser)
     */
    public CurrentUserDto getCurrentUser(String areaId, String taskId) {
        LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add( "areaId", areaId);
        params.add( "taskId", taskId);
        HttpHeaders headers = getBearToken();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        CurrentUserEntity entity = (CurrentUserEntity) HttpRequest.post(sgBaseUrl + URL_CURRENT_USER, headers, params, CurrentUserEntity.class);
        return entity.getData();
    }

    private HttpHeaders getBearToken() {
        HttpHeaders headers = new HttpHeaders();
        headers.set(KEY_AUTHORIZATION, (String) Objects.requireNonNull(Objects.requireNonNull(cacheManager.getCache(KEY_LOGIN_CACHE)).get(KEY_AUTHORIZATION)).get());
        return headers;
    }
}
